import type { CommonResponse } from '@/models'
import type { AxiosError, AxiosInstance, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from 'axios'
import { API_URL } from '@/constants'
import axios from 'axios'
import qs from 'qs'

const http: AxiosInstance = axios.create({
  withCredentials: true,
  timeout: 60000 // 请求超时
})

/**
 * 请求拦截
 */
http.interceptors.request.use((config: InternalAxiosRequestConfig) => {
  config.headers['Content-Type'] = 'application/json'
  if (localStorage.getItem('token')) {
    config.headers.token = localStorage.getItem('token')
  }

  return config
})

http.interceptors.response.use(
  (response: AxiosResponse<CommonResponse>): AxiosResponse<CommonResponse> => {
    // const res = response.data
    return response
  },
  (error: AxiosError) => {
    return Promise.reject(error)
  }
)

const request = {
  /**
   * get请求
   * @param url
   * @param params
   * @param {AxiosRequestConfig} options
   * @returns {Promise<AxiosResponse<T>>} 结果
   */
  async get<T>(url: string, params: object = {}, options?: AxiosRequestConfig): Promise<AxiosResponse<T>> {
    if (Object.keys(params).length) {
      return await http.get<T>(`${API_URL}${url}?${qs.stringify(params)}`, {
        ...options
      })
    } else {
      return await http.get<T>(`${API_URL}${url}`, {
        ...options
      })
    }
  },
  /**
   * post请求
   * @param  url
   * @param params
   * @param {AxiosRequestConfig} options
   * @returns {Promise<AxiosResponse<T>>} 结果
   */
  async post<T>(url: string, params = {}, options?: AxiosRequestConfig): Promise<AxiosResponse<T>> {
    return await http.post<T>(`${API_URL}${url}`, params, options)
  }
}

export { request }
